home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / By the Book / Learn C++ (CodeWarrior) / Chap 08.03 - overload / overload.cp < prev    next >
Text File  |  1995-10-21  |  1KB  |  90 lines

  1. #include <iostream.h>
  2. #include <fstream.h>
  3. #include <string.h>
  4.  
  5. const short kMaxNameLength = 40;
  6.  
  7.  
  8. //---------------------------------------  MenuItem
  9.  
  10. class MenuItem
  11. {
  12.     private:
  13.         float        price;
  14.         char        name[ kMaxNameLength ];
  15.  
  16.     public:
  17.         void        SetName( char *itemName );
  18.         char        *GetName();
  19.         void        SetPrice( float itemPrice );
  20.         float        GetPrice();
  21. };
  22.  
  23.  
  24. //    I added these two prototypes. They should have been here
  25. //    in the first place...  -- Dave Mark 10/20/95
  26. istream        &operator>>( istream &is, MenuItem &item );
  27. ostream     &operator<<( ostream &os, MenuItem &item );
  28.  
  29.  
  30. void    MenuItem::SetName( char *itemName )
  31. {
  32.     strcpy( name, itemName );
  33. }
  34.  
  35. char    *MenuItem::GetName()
  36. {
  37.     return( name );
  38. }
  39.  
  40. void    MenuItem::SetPrice( float itemPrice )
  41. {
  42.     price = itemPrice;
  43. }
  44.  
  45. float    MenuItem::GetPrice()
  46. {
  47.     return( price );
  48. }
  49.  
  50.  
  51. //--------------------------  iostream operators
  52.  
  53.  
  54. istream &operator>>( istream &is, MenuItem &item )
  55. {
  56.     float    itemPrice;
  57.     char    itemName[ kMaxNameLength ];
  58.     
  59.     is.getline( itemName, kMaxNameLength );
  60.     item.SetName( itemName );
  61.     
  62.     is >> itemPrice;
  63.     item.SetPrice( itemPrice );
  64.     
  65.     is.ignore( 1, '\n' );
  66.     
  67.     return( is );
  68. }
  69.  
  70. ostream &operator<<( ostream &os, MenuItem &item )
  71. {
  72.     os << item.GetName() << " ($"
  73.         << item.GetPrice() << ") ";
  74.             
  75.     return( os );
  76. }
  77.  
  78.  
  79. //---------------------------------------  main()
  80.  
  81. int    main()
  82. {
  83.     ifstream    readMe( "Menu Items" );
  84.     MenuItem    item;
  85.     
  86.     while (    readMe >> item )
  87.         cout << item << "\n";
  88.         
  89.     return 0;
  90. }